// var that = ""
class Tab {
  constructor(id) {
    // that = this
    this.main = document.querySelector(id);
    this.add = this.main.querySelector(".tabadd span");
    this.ul = this.main.querySelector(".fisrstnav ul:first-child");
    this.fsection = this.main.querySelector(".tabscon");
    this.init();
  }
  init() {
    this.update();

    this.add.onclick = this.addTab.bind(this.add, this);
    for (let i = 0; i < this.lis.length; i++) {

      this.lis[i].index = i;
      this.lis[i].onclick = this.toggle.bind(this.lis[i], this);
      this.spans[i].onclick = this.remove.bind(this.spans[i], this);
      this.fspans[i].ondblclick = this.edit;
    }
  }
  update() {
    this.spans = this.main.querySelectorAll(".fisrstnav ul li .icon-guanbi");
    this.sections = this.main.querySelectorAll(".tabscon section"); //1.先给lis添加切换事件
    this.lis = this.main.querySelectorAll(".fisrstnav ul li");
    this.fspans = this.main.querySelectorAll(".fisrstnav li span:first-child");
  }
  // 切花事件
  toggle(that) {
    that.clearClass();
    this.className = "liactive";

    that.sections[this.index].className = "conactive";
  }
  clearClass() {
    for (let i = 0; i < this.lis.length; i++) {
      this.lis[i].className = "";
      this.sections[i].className = "";
    }
  }
  addTab(that) {
    that.clearClass();
    const li = `<li class="liactive">
        <span>选项卡${Math.random().toFixed(
          2
        )}</span><span class="iconfont icon-guanbi"></span>
    </li>`;
    const content = `<section class="conactive" >测试${Math.random()}</section>`;
    that.ul.insertAdjacentHTML("beforeend", li);
    that.fsection.insertAdjacentHTML("beforeend", content);
    //         'beforebegin'：元素自身的前面。
    // 'afterbegin'：插入元素内部的第一个子节点之前。
    // 'beforeend'：插入元素内部的最后一个子节点之后。
    // 'afterend'：元素自身的后面。

    that.init();
  }
  remove(that, e) {
    e.stopPropagation();
    let index = this.parentNode.index;
    that.lis[index].remove();
    that.sections[index].remove();
    if (document.querySelector(".liactive")) return;

    index--;
    that.lis[index] && that.lis[index].click();
  }
  edit() {
    let str = this.innerHTML;
    this.innerHTML = `<input type="text" />`;
    const ipt = this.children[0];
    ipt.value = str;
    ipt.select();
    ipt.onblur = function () {
      this.parentNode.innerHTML = this.value;
    };
  }
}

new Tab("#tab");
